﻿var os = {
    path:function(){
        return window.location.protocol+'//'+location.host;
    },
    set: function (table, settings) {
        var _set = JSON.stringify(settings);
        return localStorage.setItem(table, _set);
    },
    get: function (table) {
        var data = localStorage.getItem(table);
        try {
            data = JSON.parse(data);
        } catch (err) {
            return null;
        }
        return data;
    },
    remove: function (table) {
        return localStorage.removeItem(table);
    },
    clear: function () {
        return localStorage.clear();
    },
    isJSON: function (str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return true;
                } else {
                    return false;
                }

            } catch (e) {
                return false;
            }
        }
    },
    time:function(date, fmt='yyyy-MM-dd hh:mm:s'){
        date = new Date(date)
        var o = {
            "M+" : date.getMonth()+1,                 
            "d+" : date.getDate(),                    
            "h+" : date.getHours(),                   
            "m+" : date.getMinutes(),                 
            "s+" : date.getSeconds(),                 
            "q+" : Math.floor((date.getMonth()+3)/3), 
            "S"  : date.getMilliseconds()             
        };
        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    },
    unique:function(arr) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr) && res.set(arr, 1))
    },
    uuid : function (length = 32) {
        const num =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        let str = "";
        for (let i = 0; i < length; i++) {
            str += num.charAt(Math.floor(Math.random() * num.length));
        }
        return str;
    },
    refResponseType(num){
        if(num===0){
            return 'json';
        }
    },
    getResponses(obj,sourceObj){
        if(!obj.responseBody){
            return null;
        }
        const {200:{content,description}}=obj.responseBody;
        if(!content){
            return {data:null,tip:description};
        }
        let entityPath=undefined;
        for (let k in content){
            if(content[k].schema.items){
                entityPath=content[k].schema.items.$ref;
            }
            else{
                entityPath=content[k].schema.$ref;
            }
        }
        if(!entityPath){
            return null;
        }
        entityPath=entityPath.replace('#/','');
        const pathArr=entityPath.split('/');
        const entity=sourceObj.components.schemas[pathArr[2]]
        let list=[]
        for (let k in entity.properties){
            let _summary='';
            let childrenData={};
            if(entity.properties[k].description)
                _summary=entity.properties[k].description
            if(entity.properties[k].$ref)
            {
                childrenData=os.refSchemasEntity(entity.properties[k].$ref,sourceObj)
                entity.properties[k].type=childrenData.type;
                _summary=childrenData.summary;
            }
            if(entity.properties[k].items && entity.properties[k].type==='array'){
                if(entity.properties[k].items.$ref){
                    childrenData=os.refSchemasEntity(entity.properties[k].items.$ref,sourceObj)
                }
            }
            list.push({id:os.uuid(),key:k,type:entity.properties[k].type,nullable:entity.properties[k].nullable,summary:_summary,children:childrenData.data})
        }
        return {data:list,tip:description,example:os.refSchemasJson(list)};
    },
    getParamEntity(obj,sourceObj){
        if(!obj.requestBody){
            return null;
        }
        const content=obj.requestBody.content;
        let entityPath=undefined,responeArr={},list=[];
        for (let k in content){
            entityPath=content[k].schema.$ref;
            responeArr=content[k].schema;
        }
        // respone List Array
        if(responeArr.type==='array'){
            vm.api.isBody = true;
            vm.api.body='[]';
            vm.responsesTable.push({key:responeArr.items.format,value:'[]',status:true,nullable:null,summary:null,type:responeArr.type,obj:responeArr.items.format})
            return null;
        }
        if(!entityPath){
            return null;
        }
        entityPath=entityPath.replace('#/','');
        const pathArr=entityPath.split('/');
        const entity=sourceObj.components.schemas[pathArr[2]]
        
        for (let k in entity.properties){
            let _summary='object'
            if(entity.properties[k].description)
                _summary=entity.properties[k].description
            if(entity.properties[k].items){
                entity.properties[k].type='array';
                _summary='array'
            }
            if(entity.properties[k].$ref){
                entity.properties[k].type='object';
            }
            if(entity.properties[k].format && entity.properties[k].format=='date-time'){
                entity.properties[k].type='datetime';
            }
            list.push({key:k,value:'',status:true,nullable:entity.properties[k].nullable,summary:_summary,type:entity.properties[k].type,obj:entity.properties[k]})
        }
        //console.log('list',list)
        vm.responsesTable=list;
        return list;
    },
    refBodyEntity(arr,sourceObj){
        let jsonStr='{'
        arr.forEach((item)=>{
            if(item.type==='string')
                jsonStr+='"'+item.key+'"'+':'+'"string",'
            else if(item.type==='integer')
                jsonStr+='"'+item.key+'"'+':'+'0,'
            else if(item.type==='boolean')
                jsonStr+='"'+item.key+'"'+':'+'false,'
            else if(item.type==='datetime')
                jsonStr+='"'+item.key+'"'+':'+'"'+os.time(new Date())+'",'
            else if(item.type==='array')
            {
                if(item.obj.description==='ArrayString')
                    jsonStr+='"'+item.key+'"'+':'+'["string"],'
                if(item.obj.description==='ArrayInt' || item.obj.description==='ArrayLong')
                    jsonStr+='"'+item.key+'"'+':'+'[0],'
                if(item.obj.items.$ref && item.obj.type==='array'){
                    jsonStr+='"'+item.key+'"'+':'+'[],'
                }
            }
            if(item.obj &&item.obj.$ref){
                jsonStr+='"'+item.key+'"'+':'+os.refEntity(item.obj.$ref,sourceObj)+','
                
            }
            /*else
                jsonStr+='"'+item.key+'"'+':'+'null,'*/
        })
        jsonStr=jsonStr.substr(0, jsonStr.length - 1);
        jsonStr+='}'
        //console.log('jsonStr',JSON.stringify(JSON.parse(jsonStr), null, 2))
        return JSON.stringify(JSON.parse(jsonStr), null, 2)
    },
    refEntity(path,sourceObj){
        path=path.replace('#/','');
        const pathArr=path.split('/');
        const entity=sourceObj.components.schemas[pathArr[2]]
        if(entity.type!=='object')
            return 'null';
        let list=[]
        for (let k in entity.properties){
            list.push({key:k,value:'',status:true,nullable:entity.properties[k].nullable,summary:entity.properties[k].description+'（'+entity.properties[k].type+'）',type:entity.properties[k].type,obj:entity.properties[k]})
        }
        const jsonStr=os.refBodyEntity(list,sourceObj);
        return jsonStr
    },
    refSchemasEntity(path,sourceObj){
        path=path.replace('#/','');
        const pathArr=path.split('/');
        const entity=sourceObj.components.schemas[pathArr[2]]
        let list=[]
        if(entity.enum){
            entity.enum.forEach((item)=>{
                list.push({id:os.uuid(),key:item,value:'',status:true,nullable:null,summary:entity.format,type:entity.type,obj:null})
            })
            return {data:list,type:'Enum',summary:'枚举'};
        }
        if(entity.type!=='object')
            return 'null';
        for (let k in entity.properties){
            list.push({id:os.uuid(),key:k,value:'',status:true,nullable:entity.properties[k].nullable,summary:entity.properties[k].description,type:entity.properties[k].type,obj:entity.properties[k]})
        }
        return {data:list,type:'object',summary:entity.description};
    },
    refSchemasJson(arr){
        let jsonStr='{'
        arr.forEach((item)=>{
            if(item.type==='string')
                jsonStr+='"'+item.key+'"'+':'+'"string",'
            else if(item.type==='integer')
                jsonStr+='"'+item.key+'"'+':'+'0,'
            else if(item.type==='boolean')
                jsonStr+='"'+item.key+'"'+':'+'false,'
            else if(item.type==='Enum')
                jsonStr+='"'+item.key+'"'+':'+'1,'
            else if(item.type==='datetime')
                jsonStr+='"'+item.key+'"'+':'+'"'+os.time(new Date())+'",'
            else if(item.type==='object')
                jsonStr+='"'+item.key+'"'+':'+''+os.refSchemasJson(item.children)+','
            else if(item.type==='array' && !item.children)
            {
                jsonStr+='"'+item.key+'"'+':'+'[0],'
            }
            else if(item.type==='array' && item.children)
            {
                jsonStr+='"'+item.key+'"'+':'+'['+os.refSchemasJson(item.children)+'],'
            }
        })
        jsonStr=jsonStr.substr(0, jsonStr.length - 1);
        jsonStr+='}'
        //console.log('jsonStr',JSON.stringify(JSON.parse(jsonStr), null, 2))
        return JSON.stringify(JSON.parse(jsonStr), null, 2)
    },
}